
# This file is part of the FELIX firmware distribution (https://gitlab.cern.ch/atlas-tdaq-felix/firmware/).
# Copyright (C) 2001-2021 CERN for the benefit of the ATLAS collaboration.
# Authors:
#               Andrea Borga
#               Marius Wensing
#               Israel Grayzman
#               Enrico Gamberini
#               RHabraken
#               Mesfin Gebyehu
#               William Wulff
#               Elena Zhivun
#               Rene
#               Thei Wijnen
#               Frans Schreuder
# 
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

#reset_run $IMPL_RUN
launch_runs $IMPL_RUN -jobs $CORES
#launch_runs $IMPL_RUN  -to_step write_bitstream
#cd $HDLDIR/Synt/
wait_on_run $IMPL_RUN

open_run $IMPL_RUN
current_run $IMPL_RUN

#In Vivado 2021.1 and later, we can add the RQS implementation
if { [version -short] >= 2021.1 && $ENABLE_RQS} {
    set slack [get_property SLACK [get_timing_paths -delay_type min_max]]
    if {$slack < 0 && $slack > -1.0} {
        if {[get_runs impl_2] == ""} {
            if {$TTC_SYS_SEL == $LTITTC} {
                create_run impl_2 -parent_run $SYNTH_RUN -flow {Vivado Implementation 2021}
            } else {
                create_run impl_2 -parent_run $SYNTH_RUN -flow {Vivado RQS Implementation 2021}
            }
        }
        set IMPL_RUN [get_runs impl_2]
        current_run $IMPL_RUN
        launch_runs $IMPL_RUN -jobs $CORES
        wait_on_run $IMPL_RUN
        open_run $IMPL_RUN
        set slack_run2 [get_property SLACK [get_timing_paths -delay_type min_max]]
        #Check if we actually did better the second run, otherwise use impl_1
        if {$slack_run2 < $slack} {
            puts "WNS of impl_1 was better, reverting back to impl_1"
            close_design
            set IMPL_RUN [get_runs impl_1]
            current_run $IMPL_RUN
        }
    }
}
 
file mkdir $HDLDIR/output/

set CARD_TYPE_STR $CARD_TYPE

set GIT_BRANCH [string map { / - } [exec git rev-parse --abbrev-ref HEAD]]

#In case of a Gitlab CI build, the branch defaults to HEAD with the above command, lets' get it from the environment variable CI_COMMIT_REF_NAME instead
if { [info exists ::env(CI_COMMIT_REF_NAME) ] } {
    set GIT_BRANCH [string map { / - } $env(CI_COMMIT_REF_NAME)]
}


set FileName WUPPER${CARD_TYPE_STR}_GIT_${GIT_BRANCH}_${git_tag_str}_${GIT_COMMIT_NUMBER}_${TIMESTAMP}
set IMPL_DIR [get_property DIRECTORY [current_run]]
if {$CARD_TYPE == 180 || $CARD_TYPE == 181 || $CARD_TYPE == 182 || $CARD_TYPE == 155 || $CARD_TYPE == 120} {
    launch_runs $IMPL_RUN -to_step write_device_image -jobs 8
    wait_on_run $IMPL_RUN
    set TOPLEVEL [get_property top [current_fileset]]
    file copy -force ${IMPL_DIR}/${TOPLEVEL}.pdi $HDLDIR/output/${FileName}.pdi
    #write_device_image -force $HDLDIR/output/${FileName}.pdi
    write_hw_platform -fixed -force $HDLDIR/output/${FileName}.xsa
} else { 
    write_bitstream -force $HDLDIR/output/${FileName}.bit
}


cd $HDLDIR/output/

set pass [expr {[get_property SLACK [get_timing_paths -delay_type min_max]] >= 0}]
set report [report_timing -slack_lesser_than 0 -return_string -nworst 10]
set check_timing_report [check_timing -return_string]
report_utilization -name ${FileName} -spreadsheet_table "Hierarchy" -spreadsheet_file ${HDLDIR}/output/${FileName}.xlsx -spreadsheet_depth 8 
set util [report_utilization -return_string]
set power [report_power -return_string]
set slack [get_property SLACK [get_timing_paths -delay_type min_max]]
#Add the complete GIT diff to the text file if not empty.
if {[string trim $GitDiff] != ""} {
    set GenericFileData  "There were uncommitted changes in the GIT repository while starting this build\n"    
    set gitdiffFileName "${FileName}_git.diff"
    set gitdiffFileId [open $gitdiffFileName "w"]
    puts -nonewline $gitdiffFileId $GitDiff
    close $gitdiffFileId
} else {
    set GenericFileData ""
}

set GenericFileData "$GenericFileData

Git submodule status:
$GitSubmoduleStatus

BUILD_DATETIME:                 $build_date 
COMMIT_DATETIME:                $COMMIT_DATETIME 
GIT_HASH:                       $GIT_HASH 
GIT_TAG:                        $GIT_TAG 
GIT_COMMIT_NUMBER:              $GIT_COMMIT_NUMBER 
NUMBER_OF_INTERRUPTS:           $NUMBER_OF_INTERRUPTS 
NUMBER_OF_DESCRIPTORS:          $NUMBER_OF_DESCRIPTORS
BLOCKSIZE:                      $BLOCKSIZE 
CARD_TYPE:                      $CARD_TYPE 
Timing met:                     $pass
WNS:                            $slack\n\n
Check Timing:\n
$check_timing_report\n\n
Timing Report:\n
$report\n
Utilization Report:\n
$util\n
Power report:\n
$power\n"



set GenericsFileName "${FileName}_generics_timing.txt"
set GenericsFileId [open $GenericsFileName "w"]
puts -nonewline $GenericsFileId $GenericFileData
close $GenericsFileId





write_debug_probes ${HDLDIR}/output/${FileName}_debug_nets.ltx -force

#Create MCS file. Not for VMK180 / BNL181, Versal has another concept.
if {$CARD_TYPE != 180 && $CARD_TYPE != 181 && $CARD_TYPE != 182 && $CARD_TYPE != 155 && $CARD_TYPE != 120} {
    if {$CARD_TYPE == 128 || $CARD_TYPE == 800 || $CARD_TYPE == 801} {
        write_cfgmem -force -format mcs -size 256 -interface SPIx4 -loadbit "up 0x00000000 ${FileName}.bit"  -file ${FileName}.mcs
    } else {
        write_cfgmem -force -format MCS -size 128 -interface BPIx16 -loadbit "up 0x00000000 ${FileName}.bit" ${FileName}.mcs
    }
}

cd ${HDLDIR}/output/
file delete ${FileName}.tar.gz
set ArchiveFiles [glob ${FileName}*]
if { [catch { eval exec tar -zcf ${FileName}.tar.gz ${ArchiveFiles} } msg] } {
    puts "error creating archive ${FileName}.tar.gz"
    puts $msg
}

#if {$CREATE_CHECKPOINT == 1} {
#    set IMPL_DIR [get_property DIRECTORY $IMPL_RUN]
#    set TOPLEVEL [get_property top [current_fileset] ]
#    write_checkpoint -force ${IMPL_DIR}/${TOPLEVEL}_postroute_physopt.dcp
#}
cd $scriptdir
